#include<iostream>
#include<fcntl.h>
#include <sstream>
#include <string.h>
#include<vector>
#include<fstream>
#include<map>
#include<stdlib.h>
#include"Utility.cpp"
#include"Command.cpp"

using namespace std;

/** Valid Syntaxes :
	statement -> command(space)remaining;
	remaining -> args(space)remaining;
	remaining -> | statement/<< statement/>> statement/< statement/> statement/'\0'  

*/
class CommandInterpreter {
	public:
	static Command checkRedirection(string strInput) {
		Command command;
		string red_file;
		string ind_file;
		int ind_num_char = 2;
		int red_num_char = 2;
		command.setInAppend(true);
		command.setOutAppend(true);
		bool background = false;
		int ind_index = Utility::indexOf(strInput, "<<");
		if (ind_index == -1) {
			ind_index = Utility::indexOf(strInput, "<");
			ind_num_char = 1;
			command.setInAppend(false);
		}
		int red_index = Utility::indexOf(strInput, ">>");
		if (red_index == -1) {
			red_index = Utility::indexOf(strInput, ">");
			command.setOutAppend(false);
			red_num_char = 1;
		}
		if(Utility::endswith(strInput, "&")) {
			background = true;
			strInput = Utility::trim(strInput.substr(0, strInput.length() - 1));
		}
		string commandtext = strInput;
		if (ind_index > 0) {
			if(red_index > 0) {
				if(ind_index < red_index) {
					ind_file =  strInput.substr(ind_index + ind_num_char, red_index - ind_index - ind_num_char);
					red_file =  strInput.substr(red_index + red_num_char, strInput.length() - red_index + red_num_char);
					commandtext =  strInput.substr(0, ind_index);
				} else {
					red_file =  strInput.substr(red_index + red_num_char, ind_index - red_index - red_num_char);
					ind_file =  strInput.substr(ind_index + ind_num_char, strInput.length() - ind_index - ind_num_char);
					commandtext =  strInput.substr(0, red_index);
				} 								
			} else {
				ind_file =  strInput.substr(ind_index + ind_num_char, strInput.length() - ind_num_char - ind_index);	
				commandtext =  strInput.substr(0, ind_index);				
			}
		} else if(red_index > 0) {
			red_file =  strInput.substr(red_index + red_num_char, strInput.length() - red_num_char - red_index);
			commandtext =  strInput.substr(0, red_index);		
		} 
		commandtext = Utility::trim(commandtext);
		if(ind_index > 0) {
			ind_file = Utility::trim(ind_file);
		}
		if(red_index > 0) {
			red_file = Utility::trim(red_file);
		}
		command.setCommand(commandtext.substr(0, Utility::indexOf(commandtext, " ")));
		command.setCommandWithArgs(Utility::trim(commandtext));
		command.setBackground(background);
		command.setInputFile(ind_file);
		command.setOutputFile(red_file);
		return command;
	}
};

			
	

